import express from 'express'
// import mysql2 from 'mysql2'
import mysql2 from 'mysql2/promise'

import fs from 'node:fs'
import jsyaml from 'js-yaml'

const yaml = fs.readFileSync('./db.config.yaml', 'utf-8')
const dbconfig = jsyaml.load(yaml)
console.log(dbconfig);
// const sql = mysql2.createConnection({
//     ...dbconfig.db
// })
const sql = await mysql2.createConnection({      
    ...dbconfig.db
})

const app = express()

app.use(express.json())  // 使用中间件支持post的解析

// 查询所有
// app.get('/user/list', (req, res) => {
//     sql.query('select * from user', (err, result) => {
//         res.send(result)
//     })
// })
app.get('/user/list', async (req, res) => {
    const [data] = await sql.query('select * from user')   // 数组解构 [data, other]
    res.send(data)
})

// 查询单个
app.get('/user/single/:id', async (req, res) => {
    // const [data] = await sql.query(`select * from user where id = ${req.params.id}`)   
    const [row] = await sql.query(`select * from user where id = ?`, [req.params.id])    // 支持两种传参方式, 这是占位法
    res.send(row)
})

// 增 creat
app.post('/user/add', async (req, res) => {
    const { name, gender, age, salary, comm, unitno, no, mar } = req.body

    await sql.query(`insert into user(name, gender, age, salary, comm, unitno, no, mar) values(?, ?, ?, ?, ?, ?, ?, ?)`, [name, gender, age, salary, comm, unitno, no, mar])

    res.send({code: 200})
})

// 改
app.post('/user/update', async (req, res) => {
    const { name, gender, age, salary, comm, unitno, no, mar, id } = req.body

    await sql.query(`update user set name=?, gender=?, age=?, salary=?, comm=?, unitno=?, no=?, mar=? where id=?`, [name, gender, age, salary, comm, unitno, no, mar, id])

    res.send({code: 200})
})

app.post('/user/delete', async (req, res) => {
    const { id } = req.body

    await sql.query(`delete from user where id=?`, [id])

    res.send({code: 200})
})

app.listen(9000, () => {
    console.log(9000 + '启动成功');
})